package com.kern.academic.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * JWT 操作工具类
 * Created by caoshi at 8:11 2021-06-28
 */
public class JWTUtil {


    public static final int token_expire_day = 7;
    public static final String SIGN = "!QW*d%34^JS!*#";


    /**
     * 生成token
     * @param claimMap
     * @return
     */
    public static String getToken(Map<String, String> claimMap) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, token_expire_day);
        JWTCreator.Builder builder = JWT.create();
        claimMap.forEach(builder::withClaim);
        return builder.withExpiresAt(c.getTime())
                .sign(Algorithm.HMAC256(SIGN));
    }


    /**
     * 验证token合法性
     *  非法则抛出异常
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }



}
